<?php
class Code{
    private $width;
    private $height;
    private $bgColor;
    private $img;
    //验证码长度
    private $len;
    //验证码字体大小
    private $size;
    /**
     * 构造方法
     * Code construct
     * @param null $width
     */
    public function __construct($width=null,$height=null,$bgColor=null,$len=null,$size=null){
        $this->width = is_null($width)?200:$width;
        $this->height = is_null($height)?60:$height;
        $this->bgColor = is_null($bgColor)?'#cccccc':$bgColor;
        $this->len = is_null($len)?4:$len;
        $this->size = is_null($size)?30:$size;
    }
    /**
     * 生成验证码
     */
    public function make(){
        //一、发送头部
        header('Content-type:image/png');
        //二、创建画布，然后填充
        $this->createBg();
        //三、在画布上写字
        $this->write();
        //四、干扰
        $this->makeTrouble();
        //五、输出显示
        imagepng($this->img);
        //六、销毁
        imagedestroy($this->img);
    }
    /**
     * 创建背景，然后填充
     */
    private function createBg(){
        $img = imagecreatetruecolor($this->width,$this->height);
        $color = hexdec($this->bgColor);
        imagefill($img,0,0,$color);
        $this->img = $img;
    }

    /**
     * 在画布上写字
     */
    private function write(){
        $vcode='';
        for ($i=0;$i<$this->len;$i++){
            $x = $this->width/$this->len *$i +10;
            $y = ($this->height + $this->size) / 2;
            //生成随机字符
            $text = md5(time());
            $text = $text[mt_rand(0,31)];
            $vcode .= $text;
            //随机颜色
            $textColor = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imagettftext($this->img,$this->size,mt_rand(-30,30),$x,$y,$textColor,'./tool/font.ttf',$text);
            //矩形边框
            $black = hexdec('#000000');
            imagerectangle($this->img,0,0,$this->width-1,$this->height-1,$black);
        }
        $_SESSION['vcode'] = strtoupper($vcode);
    }
    private function makeTrouble(){
        //干扰圆圈
        for ($i = 0;$i<20;$i++){
            //圆心坐标
            $cx = mt_rand(0,$this->width);
            $cy = mt_rand(0,$this->height);
            //确定圆圈的大小
            $r = mt_rand(0,20);
            //随机颜色
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imageellipse($this->img,$cx,$cy,$r,$r,$color);
        }
        //干扰线
        for ($i = 0; $i<10; $i++){
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
        }
        //干扰点
        for ($i=0;$i<100;$i++){
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
        }
    }
}
